package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyGridView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Request;

/**
 * 预约挂号医院科室选择页面
 * Created by gaoge on 2016/12/12.
 */
public class OrderListActivity extends BaseActivity implements View.OnClickListener {

    //返回键
    private ImageView img_back = null;
    //标题
    private TextView title_name = null;
    //布局文件
    private LinearLayout linearlayout = null;
    //状态列表
    private ListView state_list_ListView = null;
    //无数据页面
    private LinearLayout no_data_linearlayout = null;
    //状态列表适配器
    private StateListAdapter stateListAdapter = null;
    //分类列表适配器
    private ClassifyListAdapter classifyListAdapter = null;
    //保存数据集合
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    //记录二级菜单
    private ArrayList<HashMap<String, String>> twoList = new ArrayList<HashMap<String, String>>();
    //点击项
    private int click = 0;
    //记录上次点击项
    private int oldClick = -1;
    //加载框
    AlertDialog dialog;
    //旋转动画
    Animation rotate;
    //关闭旋转动画
    Animation closeRotate;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_list);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     * view
     */
    private void initialization() {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "预约挂号");
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        img_back = (ImageView) findViewById(R.id.img_back);
        title_name = (TextView) findViewById(R.id.title_name);
        state_list_ListView = (ListView) findViewById(R.id.state_list_listview);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        // 加载动画
        rotate = AnimationUtils.loadAnimation(OrderListActivity.this, R.anim.widget_rotate);
        closeRotate = AnimationUtils.loadAnimation(OrderListActivity.this, R.anim.close_rotate);
        // 动画执行完后停留在执行完的状态
        rotate.setFillAfter(true);
        closeRotate.setFillAfter(true);
        img_back.setOnClickListener(this);
        //状态列表添加单击事件
        state_list_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (click == -1) {
                    click = position;
                    oldClick = -1;
                } else {
                    oldClick = click;
                    if (click == position) {
                        click = -1;
                    } else {
                        click = position;
                    }
                }
                stateListAdapter.notifyDataSetInvalidated();
            }
        });
    }

    /**
     * 功能实现
     */
    private void realize() {
        //设置标题
        title_name.setText("选择医院及科室");
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(OrderListActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            getListData();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }

    }

    /**
     * 用户点击事件
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
        }
    }

    /**
     * 下载列表数据
     */
    public void getListData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.OrderList(1, 10)).get().build();
                    okhttp3.Response response = null;
                    response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    int code = response.code();
                    if (code == 204 || code == 200) {
                        if (!bodys.equals("")) {
                            JSONObject jsonObject = new JSONObject(bodys);
                            list = JSONUtil.jsonAryToListMap(jsonObject
                                    .getJSONArray("items"));
                            loginHandler.sendEmptyMessage(1);
                        } else {
                            loginHandler.sendEmptyMessage(2);
                        }
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loginHandler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 1:
                    stateListAdapter = new StateListAdapter(OrderListActivity.this, list);
                    state_list_ListView.setAdapter(stateListAdapter);
                    linearlayout.setVisibility(LinearLayout.VISIBLE);
                    no_data_linearlayout.setVisibility(LinearLayout.GONE);
                    break;
                case 2:
                    linearlayout.setVisibility(LinearLayout.GONE);
                    no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 状态列表适配器
     */
    class StateListAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;

        public StateListAdapter(Context context,
                                ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.state_list_list_item, null);
                viewHolder.gridview = (MyGridView) convertView.findViewById(R.id.gridview);
                viewHolder.textView = (TextView) convertView.findViewById(R.id.textview);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
                viewHolder.logo = (ImageView) convertView.findViewById(R.id.logo);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(getData.get(position).get("name"));

            //按钮控制
            if (click == position) {
                viewHolder.gridview.setVisibility(GridView.VISIBLE);
                // 执行动画
                viewHolder.imageView.startAnimation(rotate);
            } else {
                if (oldClick == position) {
                    // 执行动画
                    viewHolder.imageView.startAnimation(closeRotate);
                } else {
                    viewHolder.imageView.clearAnimation();
                    viewHolder.imageView.setImageResource(R.mipmap.jiantou);
                }
                viewHolder.gridview.setVisibility(GridView.GONE);
            }
            //添加二级页面数据
            try {
                JSONArray jsonArray = new JSONArray(getData.get(position).get("subCompanies"));
                twoList = JSONUtil.jsonAryToListMap(jsonArray);
                if (twoList != null && twoList.size() > 0) {
                    twoList.get(0).put("hospitalID", getData.get(position).get("id"));
                    classifyListAdapter = new ClassifyListAdapter(OrderListActivity.this, twoList);
                    viewHolder.gridview.setAdapter(classifyListAdapter);
                    final int item = click;
                    viewHolder.gridview.setFocusable(false);
                    viewHolder.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(OrderListActivity.this, OrderDoctorActivity.class);
                            intent.putExtra("hospitalID", twoList.get(0).get("hospitalID"));
                            intent.putExtra("id", twoList.get(i).get("id"));
                            intent.putExtra("name", twoList.get(i).get("name"));
                            startActivity(intent);
                        }
                    });
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    /**
     * 分类列表适配器
     */
    class ClassifyListAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;

        public ClassifyListAdapter(Context context,
                                   ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.classify_gridview_item, null);
                viewHolder.logo = (ImageView) convertView.findViewById(R.id.logo);
                viewHolder.classify_textview = (TextView) convertView.findViewById(R.id.classify_textview);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.classify_textview.setText(getData.get(position).get("name"));
            //设置图片，如果内存中有，优先从内存中读取
            if (getData.get(position).get("logo") != null && !getData.get(position).get("logo").equals("") && !getData.get(position).get("logo").equals("null")) {
                imageLoader.displayImage(getData.get(position).get("logo"), viewHolder.logo, options);
            } else {
                viewHolder.logo.setVisibility(ImageView.GONE);
                viewHolder.classify_textview.setTextColor(getResources().getColor(R.color.gray));
            }
            return convertView;
        }
    }

    /**
     * 包装类
     */
    private static class ViewHolder {
        private ImageView logo = null;
        private TextView textView = null;
        private ImageView imageView = null;
        private MyGridView gridview = null;
        private TextView classify_textview = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

}
